package com.hanxiaozhang.threadbase1ndedition.no6threadlocal;

/**
 * 〈一句话功能简述〉<br>
 * 〈ThreadLocal相关知识〉
 *
 * @author hanxinghua
 * @create 2021/11/17
 * @since 1.0.0
 */
public class No1ThreadLocal {

    public static void main(String[] args) {

        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        ThreadLocalExtend threadLocalExtend = new ThreadLocalExtend();

        // 1.方法get() 默认是空值
        System.out.println(threadLocal.get());
        threadLocal.set("hello word!");
        System.out.println(threadLocal.get());

        // 2.继承ThreadLocal，重写initialValue()，可修改默认值
        System.out.println(threadLocalExtend.get());
        threadLocalExtend.set("hello word!");
        System.out.println(threadLocalExtend.get());


        // 3.验证线程变量的隔离性
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    MyThreadLocalUtil.tl.set(Thread.currentThread().getName() + " " + (i + 1));
                    System.out.println(Thread.currentThread().getName() + "get Value = " + MyThreadLocalUtil.tl.get());
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "THREAD-A").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    MyThreadLocalUtil.tl.set(Thread.currentThread().getName() + " " + (i + 1));
                    System.out.println(Thread.currentThread().getName() + "get Value = " + MyThreadLocalUtil.tl.get());
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "THREAD-B").start();


    }

}


class MyThreadLocalUtil {

    public static ThreadLocal tl = new ThreadLocal();

}


class ThreadLocalExtend<String> extends ThreadLocal {
    @Override
    protected Object initialValue() {
        return "我是默认值 第一次get不再为null";
    }
}